package Problem02;

import java.util.Scanner;

public class LongestSubstring {
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        System.out.println("请输入要比较的第一个字符串：");
        String str1=sc.next();
        System.out.println("请输入要比较的第二个字符串：");
        String str2=sc.next();
        LongestSubstring ls=new LongestSubstring();
        String substring=ls.longestSubstring(str1,str2);
        System.out.println("最长字串为："+substring);
    }
    public  String longestSubstring(String str1,String str2){
        String tempstr;
        String Shortstr;
        String Longstr;
        String result=null;
        //取两个字符串中较短的一个
        if(str1.length()>str2.length()){
            Shortstr=str2;
            Longstr=str1;
        }
        else{
            Shortstr=str1;
            Longstr=str2;
        }
        if(Longstr.contains(Shortstr)){
            return Shortstr;
        }
        //从较短的字符串中取出子串与长字符串进行比较
        int length=Shortstr.length();
        for(int i=0;i<length;i++) {
            for (int begining = 0,ending =length-i; ending<=length; begining++,ending++) {

                    tempstr = Shortstr.substring(begining,ending);

                if (Longstr.contains(tempstr)) {
                    result = tempstr;
                    return result;
                }
            }
        }
        //检查result结果是否为空，若为空则进行处理
        if(result==null){
            result="不存在公共的子字符串";
        }
        return result;
    }
}
